package com.alibaba.csp.sentinel.dashboard.rule.nacos.degrade;

import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.AbstractRuleNacosProvider;
import com.alibaba.csp.sentinel.dashboard.rule.nacos.SentinelNacosConstants;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author marcher
 */
@Component("degradeRuleNacosProvider")
public class DegradeRuleNacosProvider extends AbstractRuleNacosProvider<List<DegradeRuleEntity>> {

    @Override
    public List<DegradeRuleEntity> getRules(String appName, String ip, Integer port) throws Exception {
        List<DegradeRule> rules = getOriginRules(appName, DegradeRule.class);
        if (CollectionUtils.isEmpty(rules)) {
            return new ArrayList<>();
        }

        return rules.stream().map(rule -> DegradeRuleEntity.fromDegradeRule(appName, ip, port, rule)).collect(Collectors.toList());
    }

    @Override
    protected String postfix() {
        return SentinelNacosConstants.DEGRADE_DATA_ID_POSTFIX;
    }
}
